package com.kamkor.interviewer.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kamkor.interviewer.client.event.CreateInterviewEvent;
import com.kamkor.interviewer.shared.InterviewDetails;

/**
 * 
 * @author kamkor
 *
 */
public class CreateInterviewPresenter implements Presenter {	
	private final Display display;
	private final HandlerManager eventBus;
	
	public interface Display {
		Button getAddButton();		
		HasValue<String> getInterviewer();
		HasValue<String> getInterviewerInitials();
		HasValue<String> getInterviewed();
		HasValue<String> getInterviewedInitials();
		Widget asWidget();	
	}
	
	public CreateInterviewPresenter(Display display, HandlerManager eventBus) {
		this.display = display;
		this.eventBus = eventBus;
	}
	
	public void bind() {
		Button button = display.getAddButton();				
		button.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				doFireCreateInterviewEvent();		
			}
		});
		button.addKeyPressHandler(new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				doFireCreateInterviewEvent();				
			}
		});
		
	}
	
	/**
	 * Fires event that if sucessful, will load interviewInfo page 
	 */
	public void doFireCreateInterviewEvent() {
		String interviewerName = display.getInterviewer().getValue();
		String interviewedName = display.getInterviewed().getValue();
		
		// group (one or more characters, zero or more white spaces) one or more times
		if(interviewerName.matches("([\\w\\-]+\\s*)+") && interviewedName.matches("([\\w\\-]+\\s*)+")) {
			String interviewerInitials = display.getInterviewerInitials().getValue();
			String interviewedInitials = display.getInterviewedInitials().getValue();					
		
			eventBus.fireEvent(
					new CreateInterviewEvent(
							new InterviewDetails(interviewerName, interviewerInitials, interviewedName, interviewedInitials)));					
		}		
	}

	@Override
	public void go(HasWidgets container) {
		bind();
		container.clear();	
		container.add(display.asWidget());		
	}	
}
